/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lt.cj.core.server;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lt.cj.config.XMLConfigWriter;
import org.lt.cj.config.entities.ConfigModel;
import org.lt.cj.core.Seed;
import org.lt.cj.model.dao.ICollectDao;
import org.lt.cj.model.impl.CollectImpl;

/**
 *
 * @author Administrator
 */
public class ServerModel {

//    private static final String INI_FILE_HEADER = "CaiJi settings File";
//    private static final String INI_FILE_NAME = "config.properties";//
//    private static final String INI_FILE_BAK = "caiji.ini.bak";
    private static final String INI_FILE_DIR = "caiji" + "_tmall";
    private static final String INI_FILE_TYPE = "model";
    private static ServerModel serverModel = new ServerModel();
    private ICollectDao dao = new CollectImpl();
    private XMLConfigWriter writer = new XMLConfigWriter();

    private ServerModel() {
    }

    public static ServerModel getInstance() {
        if (serverModel == null) {
            serverModel = new ServerModel();
            return serverModel;
        }
        return serverModel;
    }

    public void saveTask(ConfigModel configModel) {                            //将任务实例保存为任务文件

        //查看任务文件所在的路径是否存在
        String tempDir = INI_FILE_DIR;
        File iniFileDir = new File(System.getProperty("user.home") + File.separator + tempDir);
        if (!iniFileDir.exists()) {                                             //文件目录不存在的话就创建目录
            iniFileDir.mkdir();
        }
        //如果目录存在
        if (iniFileDir.exists() && iniFileDir.isDirectory()) {
            //判断任务文件存不存在，存在的话重写将其覆盖
            File iniFile = new File(System.getProperty("user.home") + File.separator + tempDir + File.separator + configModel.getTaskName() + "." + INI_FILE_TYPE);
            if (iniFile.exists()) {
                writer.saveTask(iniFile.getAbsolutePath(), configModel);
            } else {
                //如果文件不存在的话创建新文件,并将实例写到任务文件里去
                try {
                    iniFile.createNewFile();
                    writer.saveTask(iniFile.getAbsolutePath(), configModel);
                } catch (IOException ex) {
                    Logger.getLogger(ServerModel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private ConfigModel loadConfigFile(File file) {
        ConfigModel model = null;
        if (!file.exists()) {
            return null;
        } else {
            model = writer.readMallDocument(file.getAbsolutePath());
            boolean nullFlag = true;
            //循环查看这个列表是否有有效URL存在
            for (int i = 0; i < model.getSeeds().size(); i++) {
                if (!model.getSeeds().get(i).getUrl().trim().equals("") && model.getSeeds().size() != 0) {
                    nullFlag = false;
                }
            }
            /*如果文件内入口url为空，但是数据库内对应任务的URL不为空的话,
            就从数据库抽出前二十条记录放入配置实例的入口URL*/
            if (nullFlag && dao.getUnvisitCountByTask(model.getTaskName()) > 0) {

                nullFlag = false;
                List<Seed> seeds = dao.getUnvisitedSeeds(model.getTaskName(), 20);
                List<Seed> unvisitedSeeds = new ArrayList<Seed>();
                int index = 0;
                for (Iterator it = seeds.iterator(); it.hasNext();) {
                    unvisitedSeeds.add((Seed) it.next());
                    index = index + 1;
                }
                model.setSeeds(unvisitedSeeds);
            }

            if (nullFlag) {
                //文件的任务实例的入口url为空，表示这个任务已经采集完成，可以将其设置为null并将文件删除
                model = null;
//                if (file.delete()) {
//                    System.out.println("file delete success");
//                } else {
//                    System.out.println("file delete fail");
//                    file.deleteOnExit();
//                }
            }
        }
        return model;
    }

    public ConfigModel[] loadTasks() {

        ConfigModel[] tasks = null;
        //找到任务文件的所在目录
        File iniFile = new File(System.getProperty("user.home") + File.separator + this.INI_FILE_DIR);

        //判断该文件是否为目录且该目录存在，否则返回空任务
        if (iniFile.exists() && iniFile.isDirectory()) {
            File[] files = iniFile.listFiles(new MyFileFilter());               //获取该目录的文件列表
            if (files.length > 0) {                                             //如果文件存在才允许加载任务

                tasks = new ConfigModel[files.length];
                for (int i = 0; i < files.length; i++) {                        //循环加载任务实例
                    System.out.println("" + files[i].getAbsolutePath());
                    tasks[i] = loadConfigFile(files[i]);
                }
                return tasks;
            }
        }
        return null;
    }

    private void deleteAllFile() {
        File iniFile = new File(System.getProperty("user.home") + File.separator + this.INI_FILE_DIR);
        File[] files = iniFile.listFiles(new MyFileFilter());                   //获取该目录的文件列表
        for (int i = 0; i < files.length; i++) {
            if (files[i].exists()) {
                if (files[i].delete()) {
                    System.out.println("file deleted success");
                } else {
                    System.out.println("file deleted fail");
                }
            }
        }
    }

    class MyFileFilter implements FileFilter {

        public boolean accept(File pathname) {
            if (pathname.getAbsolutePath().endsWith(ServerModel.INI_FILE_TYPE)) {
                return true;
            }
            return false;
        }
    }
}
